<template>
	<view>
		<view class="content">
			<u-navbar :fixed="false" :title="titleName" :autoBack="true" :safeAreaInsetTop="true" leftIconColor="#fff">
			</u-navbar>

			<view class="topMainForm f-dc"
				style="padding: 20rpx;max-height: 30vh;position: relative;background-color: #fff;">
				<view class="content_main_CardBox"
					style="border-radius: 15rpx;background-color: #4499ec;flex: 1;overflow: auto;padding: 20rpx 30rpx;color: #fff;">
					<view class="x-f" style="font-size: 28rpx;padding: 8rpx 0;font-weight: 600;">
						<text>No:{{formData.BillNO}}</text>
					</view>
					<view style="font-size: 20rpx;" class="f-dc">
						<view style="margin-bottom: 6rpx;">负责人员：{{formData.CuratorName}}</view>
						<view style="margin-bottom: 6rpx;">检验方案：{{formData.ProjectName}}</view>
						<view style="margin-bottom: 6rpx;">检验期限：{{formData.TestEndTime}}</view>
						<view style="margin-bottom: 6rpx;">任务进度：0 / <text>{{formData.CJNum}}</text></view>
					</view>

					<!-- 已审核标记 -->
					<uni-icons fontFamily="CustomFontPlatform" color="#b3ffd6"
						style="position: absolute;right: 20rpx;top: 20rpx;"
						size="100rpx">{{$utils.toUniCode('&#xeda6;')}}</uni-icons>
				</view>
			</view>

			<u-sticky style="background-color: #fff;top: 0 !important;">
				<u-tabs keyName="title" :list="TabList" :is-scroll="false" :current="tabCurrent" @change="clickTabItem"
					activeStyle="color: #51d0d0;" lineWidth="60" lineColor="#51d0d0" :scrollable="false">
					<template #TabText="{element,index}">
						<view style="font-size: 14px;">{{element.title}}</view>
					</template>
				</u-tabs>
				<view style="height: 8rpx;width: 100%;background-color: #f2f1f6;"></view>
			</u-sticky>

			<view class="flex-auto" style="padding: 7rpx 15rpx 15rpx;">
				<!-- 任务进度 -->
				<view v-show="tabCurrent == 0">
					<view class="child-card" v-for="(item, index) in tableData" :key="item.LabTestProductDeID"
						@click="openReportTable(item)">
						<!-- 顶部项目信息 -->
						<view class="child-card-top x-f">
							<view class="child-card-top__left x-f">
								<view class="ordinal">{{ index + 1 }}</view>
								<view class="title">{{ item.LabTestPlanContent }}</view>
							</view>
							<view class="child-card-top__right x-f">
								<u-tag plain :text="item.SFJY ? '已检验' : '未检验'" :type="item.SFJY ? 'success' : 'warning'"
									size="mini" />
								<u-tag v-if="item.Approve && item.SFJY" style="margin-left: 8rpx" plain text="已审核"
									type="success" size="mini" />
							</view>
						</view>
						<view style="font-size: 24rpx;margin-top: 10rpx;">检验项数量：{{item.Details.length}}</view>

						<!-- 子子表：样品信息 -->
						<view class="sample-list" v-if="item.Details && item.Details.length">
							<view class="sample-box" v-for="(sample, sIndex) in item.Details" :key="sIndex">
								<view class="sample-header">
									{{sample.LabTestProjectName}}
									<text :class="[
					            'sample-status',
					            sample.FResult == 1 ? 'ok' :
					            sample.FResult === 0 ? 'fail' : 'pending'
					          ]">
										{{ sample.Result || '待检验' }}
									</text>
								</view>
								<view class="sample-info">检验时间：{{ sample.TestTime || '--' }}</view>
								<view class="sample-info">检验人员：{{ sample.Tester || '--' }}</view>
							</view>
						</view>
					</view>

				</view>


				<view v-show="tabCurrent == 1">
					<view class="childCardBox">
						<view class="x-f">
							<view class="x-f"
								style="background-color: #c8eed5;width: 24px;height: 24px;border-radius: 9999px;justify-content: center;zoom: .6;">
								<view style="background-color: #40d37d;width: 14px;height: 14px;border-radius: 9999px;">
								</view>
							</view>
							<text style="font-size: 15px;color: #999;margin-left: 4px;">2025-06-06</text>
						</view>

						<view class="childCardBox_commonBox x-bc"
							style="flex:1;border-radius: 8px;background-color: #f7f7f7;padding: 10px;margin-top: 15px;">
							123
						</view>

					</view>
				</view>

			</view>

			<view class="content_bottom1 x-ec" :style="$utils.disposeSafeBottomFun()">
				<view class="x-ec">
					<button class="CommonBtnSize content_bottom_primary_Btn"
						@click="openBaseScreenByTree('设备',2)">测试树型</button>


					<button :disabled="!enabledSubmitBtn" class="CommonBtnSize content_bottom_primary_Btn"
						@click="changeApprove">撤审</button>
				</view>
			</view>

		</view>

		<m-pda-scancode v-if="$utils.isPda()" :listenName="pdaListenCurrent"
			:SetContent="{action:$store.state.systemConfig.sysDeviceInfo.broadcastAction,extra:$store.state.systemConfig.sysDeviceInfo.broadcastResult}"></m-pda-scancode>

		<m-loading :text="loadingText" v-model="showMLoading" :showClose="false" :loaderActive="loaderActive"
			maskBackgroundColor="rgba(0,0,0,0.3)"></m-loading>
	</view>
</template>

<script>
	import layerFun from '@/common/comFun/layerFun.js';
	var layer = layerFun;
	export default {
		data() {
			return {
				LabTestProductID: null, // 主键ID
				enabledSubmitBtn: false, // 控制按钮是否启用
				showMLoading: false, // 加载动画
				loadingText: "正在渲染",
				loaderActive: "loading",

				titleName: "xxxx检验项",

				formData: {
					ObjectName: '',
					BillNo: '',
					Inspection: '',
					InspectionPrice: '',
				},
				TabList: [{
					title: "任务进度"
				}, {
					title: "任务记录"
				}],
				tabCurrent: 0,

				tableData: [], // 列表数据

				ChoiceDataData: null, // 测试树形的选中数据
			};
		},
		computed: {
			selectTreeListenCurrent() { // 树型选择监听器名称
				let routes = getCurrentPages(); //当前页面栈
				return "selectTree" + routes.length;
			},

			pdaListenCurrent() { // pda监听器名称
				let routes = getCurrentPages(); //当前页面栈
				// pda监听器
				return "pdaScanCode" + routes.length;
			},
		},
		onReady() {},
		onLoad(option) {
			console.log(option);
			this.LabTestProductID = option.LabTestProductID;

			this.getPageInfoByID();
		},
		mounted() {
			let that = this;
			that.$nextTick(() => {
				that.enabledSubmitBtn = true;
			});


			uni.$on(that.selectTreeListenCurrent, (ret => {
				console.log(ret);
				if (ret.chooseType == 1) {
					that.ChoiceDataData = ret.data.EquipmentID
				} else {
					that.ChoiceDataData = ret.data.map(item => {
						return item.EquipmentID
					})
				}
				// that.$utils.layer.alert(JSON.stringify(ret))
			}));

			// 组件中监听队列完成
			this.$onQueueEvent('queueEmpty', () => {
				// 当所有事件加载完成后：
				// 开放按钮点击权限
				console.log('页面所有请求完成');

				that.$utils.hideLoading();
				this.showMLoading = false;
				that.enabledSubmitBtn = true; // 解开按钮限制
			});

			this.$onQueueEvent('requestFail', (ret) => {
				// 当所有事件加载完成后：
				// 开放按钮点击权限
				console.log('edit_requestFail');
				console.log(ret);

			});
		},
		methods: {
			// tabs标签
			clickTabItem(data) {
				let that = this;
				this.tabCurrent = data.index;

			},

			// 取值
			getPageInfoByID() { // 根据LabTestProductID获取页面信息
				let that = this;

				that.$request("Qu_LabTestSelectDetails", {
					LabTestProductID: that.LabTestProductID
				}, function(ret) {
					console.log(ret);
					if (ret.status == 200) {
						let {
							ds,
							ds1,
							ds2
						} = ret.data;

						if (ds.length) {
							Object.assign(that.formData, ds[0]);
						}

						let mergeData = that.mergeDs1AndDs2(ds1, ds2);
						console.log(mergeData);
						that.tableData = mergeData;

					}
				})
			},
			mergeDs1AndDs2(ds1, ds2) {
				// 构建一个以 LabTestProductDeID 为 key 的数组映射
				const detailsMap = ds2.reduce((acc, item) => {
					const key = item.LabTestProductDeID;
					if (!acc[key]) acc[key] = [];
					acc[key].push(item);
					return acc;
				}, {});

				// 遍历 ds1，为每项添加对应的 details（ds2 子项）
				return ds1.map(item => ({
					...item,
					Details: detailsMap[item.LabTestProductDeID] || []
				}));
			},

			// 交互事件
			openReportTable(item) { // 点击进入任务表格详情

				uni.hideToast();

				console.log(item);
				plus.screen.lockOrientation('landscape-primary');

				setTimeout(() => {
					uni.navigateTo({ // 前往表单界面 lucksheet
						url: '/st_qms/LabReport/DocumentPageByReport' + '?keyID=' + item.LabTestProductID +
							'&keyDeID=' + item.LabTestProductDeID
					});
				}, 300)
			},
			changeApprove() {
				let that = this;
				if (!this.enabledSubmitBtn) {
					return;
				}
				this.enabledSubmitBtn = false;
				this.loadingText = "正在撤审";
				this.showMLoading = true;
				this.loaderActive = "loading";

				setTimeout(() => {
					that.loadingText = "已撤审";
					that.loaderActive = "success";
					setTimeout(() => {
						that.enabledSubmitBtn = true;
						that.showMLoading = false;
					}, 1000);
				}, 1000);

			},


			openBaseScreenByTree(str, type) { // 树型
				let that = this;

				let config = {
					requestType: "$request", // 请求方法
					chooseType: type, // 是否单选
					colName: str, // 返回标识

					showSearch: true, // 是否可搜索
					SearchKey: "SearchKey",
					cmd: "getEquipmentBySBFLID", // 接口名
					keyName: "EquipmentName", // 显示值
					keyValue: "EquipmentID", // 隐藏值
					ChoiceDataData: this.ChoiceDataData || null,
					isPaging: true, // 是否分页
					pageIndexStr: "pageIndex",
					param: {
						SearchKey: "",
						EquipmentTypeID: '',
						pageIndex: 1,
						pageSize: 30,
					},
					subText: [{
						label: "编号：",
						labelKey: "EquipmentCode"
					}, {
						label: "规格：",
						labelKey: "EquipmentSpec"
					}, ],

					treeCofig: { // 树型的参数
						treeRequestType: "$request", // 请求方法
						treePath: "sbfl_XL", // 树接口名
						treeDisplayValue: "EquipmentTypeName",
						treeHiddenValue: "EquipmentTypeID",
						treeParentValues: "UpID",
						treeParams: {}
					},

				};

				that.$store.commit("ChangeAndSetStateData", {
					Name1: "BaseScreenParmByTree",
					data: config
				})

				console.log(config);
				uni.navigateTo({
					url: "/commonPage/Tool/baseScreenByTree" + "?listen=" + that.selectTreeListenCurrent
				})
			},
		}
	}
</script>

<style lang="scss">
	.content {
		.form {
			background-color: #fff;
			padding: 15rpx;
		}

		.child-card {
			background-color: #fff;
			padding: 24rpx;
			margin-bottom: 24rpx;
			border-radius: 16rpx;
			box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.04);
			font-size: 26rpx;

			.child-card-top {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding-bottom: 20rpx;
				border-bottom: 1rpx solid #f0f0f0;

				&__left {
					display: flex;
					align-items: center;

					.ordinal {
						width: 32rpx;
						height: 32rpx;
						border-radius: 50%;
						background-color: #51d0d0;
						color: #fff;
						font-size: 24rpx;
						text-align: center;
						line-height: 32rpx;
						font-weight: bold;
					}

					.title {
						font-weight: 600;
						font-size: 28rpx;
						color: #1a1a1a;
						margin-left: 12rpx;
					}
				}

				&__right {
					display: flex;
					align-items: center;
				}
			}

			.sample-list {
				display: flex;
				flex-wrap: wrap;
				margin-top: 16rpx;
				gap: 16rpx;
				max-height: 370rpx;
				overflow: auto;

				.sample-box {
					flex: 1 1 calc(50% - 16rpx); // 两列布局
					background-color: #f8f9fb;
					border-radius: 12rpx;
					padding: 16rpx;
					min-width: 45%;
					box-sizing: border-box;

					.sample-header {
						display: flex;
						justify-content: space-between;
						font-weight: 500;
						font-size: 26rpx;
						margin-bottom: 8rpx;

						.sample-status {
							font-weight: bold;
							font-size: 24rpx;

							&.ok {
								color: #4caf50;
							}

							&.fail {
								color: #f44336;
							}

							&.pending {
								color: #999;
							}
						}
					}

					.sample-info {
						font-size: 24rpx;
						color: #666;
						margin-top: 4rpx;
					}
				}
			}
		}


		.content_bottom1 {
			background-color: #fff;
			display: flex;
			align-items: center;
			justify-content: flex-end;
			height: 70px;
			line-height: 70px;
			padding: 6px 15px;
			border-top: 2px solid #f2f2f2;

			.workBtn {
				border-color: #ddd !important;
				margin-left: 10px !important;

				&.small-font {
					font-size: 12px !important;
				}

				&:not(.small-font) {
					font-size: 14px;
				}
			}
		}
	}
</style>